# coding=utf-8
import datetime
import string
from control import *

from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from loginTool import login_required

class ContentClass(db.Model):       #普通内容主表（包含级别和内容）
      maincode  = db.StringProperty(multiline=True) #存第一级内容编号，后面的表都加上  
      code = db.StringProperty(multiline=True)      #编码（手工编码）
      content = db.TextProperty()   #内容
      title = db.StringProperty(multiline=True)     #抬头标题
      father = db.StringProperty(multiline=True)    #//父级内容编码，当父级为空时level为0
      level= db.StringProperty(multiline=True)      #//级别 从上到下分别0、1-5，level为0是唯一
      lastUpdateTime = db.DateTimeProperty(auto_now_add=True)  #//上次更新时间
      updateSpanTime = db.StringProperty(multiline=True)  #//更新间隔时间
      status = db.StringProperty(multiline=True)       #//状态 0修改删除，10天后自动删除，1为不删除
      imglist=db.ListProperty(item_type=int)
      photolist=db.ListProperty(item_type=int)

class ReplyContent(db.Model):       #//需回复的内容表（调查等需要用户回复的内容）
      maincode  = db.StringProperty(multiline=True) #存第一级内容编号，后面的表都加上  
      code = db.StringProperty(multiline=True)    #//编码（手工编码）
      content = db.TextProperty() #//内容
      father = db.StringProperty(multiline=True)  #//父级内容编码
      level= db.StringProperty(multiline=True)    #//级别 从上到下分别1-3
      replyType = db.StringProperty(multiline=True) #//回复类别 1：文本回复  2、单选选择回复 3、多选选择回复
      status = db.StringProperty(multiline=True)       #//状态
      lastUpdateTime = db.DateTimeProperty(auto_now=True)#//上次更新时间
      imglist=db.ListProperty(item_type=int)
      photolist=db.ListProperty(item_type=int)
      
class PublicPage(webapp.RequestHandler):
  def render(self, template_file, template_value):
      path = os.path.join(os.path.dirname(__file__), template_file)
      self.response.out.write(template.render(path, template_value))
        
class ContentList(PublicPage):
  @login_required
  def get(self,page):
      prevValue = self.request.get('prevValue')
      father = self.request.get('father')
#      self.response.out.write(deleteTimedContent())
      #return
      if father =='':
          level = '1'
          contents = db.GqlQuery("SELECT * FROM ContentClass WHERE level = :1 ORDER BY code ASC", level)
          totalcount=contents.count(limit=1000000)
      else:
          level = str(CodeLength(father)+1)
          contents = db.GqlQuery("SELECT * FROM ContentClass WHERE father=:1 ORDER BY code ASC",father)
          totalcount=contents.count(limit=1000000)
      if level=='5':
          level = None
      fatherList = findFather(father)
      index=0 if page=="" else int(page)
      num=0 if index==0 else 1
      contents = contents.fetch(16+2^num,index*16-num)
      count=len(contents)
      for i in range(count):
          p,n=None,None
          c=contents[i]
          if i<count-1:
              n=contents[i+1]
          if i!=0:
              p=contents[i-1]
          if p:
              c.prev=p.code
          if n:
              c.next=n.code
      if num==1:
          contents=contents[1:17]   
      else:
          contents=contents[0:16] 
      if index!=0:
          if len(contents)==0:
              self.redirect('/contentList/%s?father=%s' %(index-1,father))  
      prev,next=None,None
      if len(contents)>0:
          if contents[0].__dict__.has_key('prev') :
              prev=contents[0].prev
          else:
              prev=None
          next=contents[0].code
      prevpage,nextpage=getPageing(len(contents), index)
      template_values = {"contents":contents,"contentlength":len(contents),"fatherList":fatherList,"prev":prev,"next":next,"prevpage":prevpage,"nextpage":nextpage,"index":index,"father":father,"level":level,"prevValue":prevValue,'lastpage':totalcount/16}
      self.render('template/content/zxlist.html',template_values)
      #self.render('html/contentManage/contentList.html',template_values)
  @login_required
  def post(self,page):
      father = self.request.get('hidden')
      prev = self.request.get('prev')
      code = self.request.get('code')
      next = self.request.get('next')
      prevValue = self.request.get('prevValue')
      if self.request.get('do')==u'插入':
          next=code
      if self.request.get('do')==u'添加':
          prev=code
      if not code:
          prev=self.request.get('prevcode')
          next=self.request.get('nextcode')
      self.redirect('/contentAdd?father=%s&prev=%s&next=%s&prevValue=%s&page_id=%s' %(father,prev,next,prevValue,page))
class ContentAdd(PublicPage):
  @login_required
  def get(self):
      father = self.request.get('father')
      prev = self.request.get('prev')
      next = self.request.get('next')
      prevValue = self.request.get('prevValue')
      page = self.request.get('page_id')
      if(prevValue != '' and prev==''):#分页后下一页调用
          prev = prevValue
      newAddCode = AutoCode(father,prev,next)
      if (CodeLength(newAddCode)==1):#父类层，maincode与code相同
          maincode = newAddCode
          father = ''
      if (CodeLength(newAddCode)>=2):
          maincode = getMainCode(newAddCode)  
      template_values = {"newAddCode":newAddCode,"maincode":maincode,"father":father,"page":page,}
      self.render('template/content/contentAdd.html',template_values)
#      self.render('html/contentManage/contentAdd.html',template_values)
  @login_required
  def post(self):
      content = ContentClass()
      page = self.request.get('page_Id')
      content.maincode = self.request.get('maincode').replace('\r','').replace('\n','')
      content.code = self.request.get('code').replace('\r','').replace('\n','')
      content.title = self.request.get('title').replace('\r','').replace('\n','')
      content.content = self.request.get('content').replace('\r\n','[()]').replace('\n','[()]').replace('[()][()]','[()]').replace('[()][()]','[()]')
      content.updateSpanTime = self.request.get('updateSpanTime').replace('\r','').replace('\n','')
      father = content.father = self.request.get('father').replace('\r','').replace('\n','')
      if content.father=="":
            content.level = "1"
      else:
            content.level = str(CodeLength(content.father)+1)
      content.status = "1"
      content.put()
      self.redirect('/contentList/%s?father=%s' %(page,father))

class ContentDelete(PublicPage):
  @login_required
  def get(self):
      contentCode = self.request.get('contentCode')
      pageId = self.request.get('page_id')
      father = self.request.get('father')

      contentList = []
      contents = db.GqlQuery("SELECT * FROM ContentClass WHERE code=:1 ",contentCode)
      if contents:
          for content in contents:
              if content.status == '1':
                    content.status = '0'
                    content.lastUpdateTime = datetime.datetime.now()
                    db.put(content)
#              contentList.append(content)
              contentList=findChildNodes(contentList,content.code)
              for cList in contentList:
                  db.delete(cList)
      self.redirect('/contentList/%s?father=%s' %(pageId,father))

class ContentUpdate(PublicPage):
  @login_required
  def get(self):
      contentCode = self.request.get('contentCode')
      index = self.request.get('page_id')
      father = self.request.get('father')
      if index=="":
          index='0'
      index = string.atoi(index)
    
      contentList = []
      contents = db.GqlQuery("SELECT * FROM ContentClass WHERE code=:1 ",contentCode)
      replyContents = db.GqlQuery("SELECT * FROM ReplyContent WHERE code=:1 ",contentCode)
      if contents:
          for content in contents:
              contentList.append(content)#进入List
#              contentList=findChildNodes(contentList,content.code)
      if replyContents:
          for replyContent in replyContents:
              contentList.append(replyContent)#进入List
#              contentList=findChildNodes(contentList,replyContent.code)
      template_values={"contentList":contentList,"index":index,"father":father,}
      self.render('template/content/contentUpdate.html', template_values)
#      self.render('html/contentManage/contentUpdate.html', template_values)
  @login_required
  def post(self):
      pageId = self.request.get('page_id')
      father = self.request.get('father')
      contentList = self.request.get('contentList')
      contentList = contentList.split(',')
      for i in range(len(contentList)):
          if (contentList[i].find('s')!=-1):#特殊节点
              replyContents = db.GqlQuery("SELECT * FROM ReplyContent WHERE code=:1",contentList[i])
              if replyContents:
                  for replyContent in replyContents:
                      replyContent.replyType = self.request.get('replyType_'+contentList[i])
                      replyContent.content = self.request.get('content_'+contentList[i]).replace('\r\n','[()]').replace('\n','[()]').replace('[()][()]','[()]').replace('[()][()]','[()]')
                      replyContent.lastUpdateTime = datetime.datetime.now()
                      replyContent.status = self.request.get('status_'+contentList[i])
                      db.put(replyContent)
          else:
              contents = db.GqlQuery("SELECT * FROM ContentClass WHERE code=:1",contentList[i])
              if contents:
                  for content in contents:
                      content.title = self.request.get('title_'+contentList[i])
                      content.content = self.request.get('content_'+contentList[i])
                      content.lastUpdateTime = datetime.datetime.now()
                      content.updateSpanTime = self.request.get('updateSpanTime_'+contentList[i])
                      content.status = self.request.get('status_'+contentList[i])
                      db.put(content)
      self.redirect('/contentList/%s?father=%s' %(pageId,father))
            
class ReplyContentList(PublicPage):
  @login_required
  def get(self,page):
      prevValue = self.request.get('prevValue')
      father = self.request.get('father')
      if father =='':
          replyContents = db.GqlQuery("SELECT * FROM ReplyContent ORDER BY father ASC")
          totalcount=replyContents.count(limit=1000000)
          replyContentFather=''
      else:
          replyContents = db.GqlQuery("SELECT * FROM ReplyContent WHERE father=:1 ORDER BY code ASC",father)
          totalcount=replyContents.count(limit=1000000)
          if (father.find('s')==-1) and replyContents.count()==0:
              replyContentFather = '0'
          if (father.find('s')==-1) and replyContents.count()!=0:
              replyContentFather = '1'
          if (father.find('s')!=-1):
              replyContentFather = '2'
      fatherList = findFather(father)
      index=0 if page=="" else int(page)
      num=0 if index==0 else 1
      replyContents = replyContents.fetch(16+2^num,index*16-num)
      count=len(replyContents)
      for i in range(count):
          p,n=None,None
          c=replyContents[i]
          if i<count-1:
              n=replyContents[i+1]
          if i!=0:
              p=replyContents[i-1]
          if p:
              c.prev=p.code
          if n:
              c.next=n.code
      if num==1:
          replyContents=replyContents[1:17]   
      else:
          replyContents=replyContents[0:16]
      prev,next=None,None
      if len(replyContents)>0:
          if replyContents[0].__dict__.has_key('prev') :
              prev=replyContents[0].prev
          else:
              prev=None
          next=replyContents[0].code             
      if len(replyContents)==0:
          if father.find('s')==-1:
              self.redirect("/contentList/0?father=%s" %father)
          pass
      prevpage,nextpage=getPageing(len(replyContents), index)
      template_values = {"replyContents":replyContents,"fatherList":fatherList,"prev":prev,"next":next,"prevpage":prevpage,"nextpage":nextpage,"index":index,
                         "father":father,"prevValue":prevValue,"replyContentFather":replyContentFather,'lastpage':totalcount/16}
      self.render('template/content/replyContentList.html',template_values)
#      self.render('html/contentManage/replyContentList.html',template_values)
  @login_required
  def post(self,page):
      father = self.request.get('hidden')
      prev = self.request.get('prev')
      code = self.request.get('code')
      next = self.request.get('next')
      if self.request.get('do')==u'插入':
          next=code
      if self.request.get('do')==u'添加':
          prev=code
      if not code:
          prev=self.request.get('prevcode')
          next=self.request.get('nextcode')
      prevValue = self.request.get('prevValue')
      self.redirect('/replyContentAdd?father=%s&prev=%s&next=%s&prevValue=%s&page_id=%s' %(father,prev,next,prevValue,page))

class ReplyContentAdd(PublicPage):
  @login_required
  def get(self):
      father = self.request.get('father')
      prev = self.request.get('prev')
      next = self.request.get('next')
      prevValue = self.request.get('prevValue')
      page = self.request.get('page_id')
        
      if(prevValue != '' and prev==''):#分页后下一页调用
          prev = prevValue
      newAddCode = AutoCode(father,prev,next)
      newAddCode = getReplyCode(newAddCode)#为编号加特殊标记's'，newAddCode有's'则直接返回
      maincode = getMainCode(newAddCode)
          
      template_values = {"newAddCode":newAddCode,"maincode":maincode,"father":father,"page":page,}
      self.render('template/content/replyContentAdd.html',template_values)
#      self.render('html/contentManage/replyContentAdd.html',template_values)
  @login_required
  def post(self):
      replyContent = ReplyContent()
      page = self.request.get('page_Id')
      replyContent.maincode = self.request.get('maincode').replace('\r','').replace('\n','')#主编号
      replyContent.code = self.request.get('code').replace('\r','').replace('\n','')#编号
      replyContent.content = self.request.get('content').replace('\r\n','[()]').replace('\n','[()]').replace('[()][()]','[()]').replace('[()][()]','[()]')#内容
      replyContent.replyType = self.request.get('replyType').replace('\r','').replace('\n','')
      replyContent.status = '1'
      father = replyContent.father = self.request.get('father').replace('\r','').replace('\n','')
      replyContents = db.GqlQuery("SELECT * FROM ReplyContent WHERE code=:1",father).fetch(1)
      if len(replyContents)==1:
          replyContent.level = str(int(replyContents[0].level)+1)
      else:
          replyContent.level='100'
      replyContent.put()
      self.redirect('/replyContentList/%s?father=%s' %(page,father))

class ReplyContentDelete(PublicPage):
  @login_required
  def get(self):
      contentCode = self.request.get('replyContentCode')
      pageId = self.request.get('page_id')
      father = self.request.get('father')

      replyContentList = []
      replyContents = db.GqlQuery("SELECT * FROM ReplyContent WHERE code=:1 ",contentCode)
      if replyContents:
          for replyContent in replyContents:
            #历遍子节点
              #replyContent.status = '0'
              #replyContent.lastUpdateTime = datetime.datetime.now()
              #db.put(replyContent)
              replyContentList.append(replyContent)
              replyContentList=findChildNodes(replyContentList,replyContent.code)
              for rList in replyContentList:
                  db.delete(rList)
      self.redirect('/replyContentList/%s?father=%s&replytype=1' %(pageId,father))
              

########资讯编号############################
  #处理code，判断是第几层资讯
def CodeLength(code): #返回数字是多少，说明是第几层
    codelist = code.split('-')
    layer = len(codelist)
    return layer

def AutoCode(father,prev,next):
    numlist=['0','1','2','3','4','5','6','7','8','9']
    if prev and  prev[-1] not in numlist:
        prev=prev[:-1]
    if next and next[-1] not in numlist:
        next=next[:-1]
    newAddCode =''
    prevLength = CodeLength(prev)
    nextLength = CodeLength(next)
    if (prevLength == 1 and nextLength == 1 and father==''):
      #说明是父类层
      if (prev =='' and next ==''):
        #说明目前没有父类层的资讯,maincode 为空
        newAddCode = 'a4'
        return newAddCode;
      elif (prev=='' and next !=''):
        prev_Part_Str = PartingString(next)
        next_Part_Str = NextString(next)
        is_Special_Point = isSpecialPoint(next_Part_Str)
        no_Letter_Part = isContainLetter(next_Part_Str)
        newCode = Rule(prev,no_Letter_Part)
        if (is_Special_Point==0):
          return (prev_Part_Str+'a'+newCode)
        elif (is_Special_Point==1):
          return (prev_Part_Str+'s'+newCode)
        else:
          return (prev_Part_Str+newCode)
      elif (prev!='' and next ==''):
        prev_Part_Str = PartingString(prev)
        next_Part_Str = NextString(prev)
        is_Special_Point = isSpecialPoint(next_Part_Str)
        no_Letter_Part = isContainLetter(next_Part_Str)
        newCode = Rule(no_Letter_Part,next)
        if (is_Special_Point==0):
          return (prev_Part_Str+'a'+newCode)
        elif (is_Special_Point==1):
          return (prev_Part_Str+'s'+newCode)
        else:
          return (prev_Part_Str+newCode)
      else:
        prev_Part_Str_1 = PartingString(prev)
        next_Part_Str_1 = NextString(prev)
        is_Special_Point_1 = isSpecialPoint(next_Part_Str_1)
        no_Letter_Part_1 = isContainLetter(next_Part_Str_1)
        prev_Part_Str_2 = PartingString(next)
        next_Part_Str_2 = NextString(next)
        is_Special_Point_2 = isSpecialPoint(next_Part_Str_2)
        no_Letter_Part_2 = isContainLetter(next_Part_Str_2)
        newCode = Rule(no_Letter_Part_1,no_Letter_Part_2)
        if (is_Special_Point_2==0):
          return (prev_Part_Str_2+'a'+newCode)
        elif (is_Special_Point_2==1):
          return (prev_Part_Str_2+'s'+newCode)
        else:
          return (prev_Part_Str_2+newCode)
    else:
      fatherLength = CodeLength(father)
      if (prev =='' and next ==''):
        #说明目前没有父类层的资讯,maincode 为空
        newAddCode = father+'-4'
        return newAddCode;
      elif (prev=='' and next !=''):
        prev_Part_Str = PartingString(next)
        next_Part_Str = NextString(next)
        is_Special_Point = isSpecialPoint(next_Part_Str)
        no_Letter_Part = isContainLetter(next_Part_Str)
        newCode = Rule(prev,no_Letter_Part)
        if (is_Special_Point==0):
          return (prev_Part_Str+'a'+newCode)
        elif (is_Special_Point==1):
          return (prev_Part_Str+'s'+newCode)
        else:
          return (prev_Part_Str+newCode)
      elif (prev!='' and next ==''):
        prev_Part_Str = PartingString(prev)
        next_Part_Str = NextString(prev)
        is_Special_Point = isSpecialPoint(next_Part_Str)
        no_Letter_Part = isContainLetter(next_Part_Str)
        newCode = Rule(no_Letter_Part,next)
        if (is_Special_Point==0):
          return (prev_Part_Str+'a'+newCode)
        elif (is_Special_Point==1):
          return (prev_Part_Str+'s'+newCode)
        else:
          return (prev_Part_Str+newCode)
      else:
        prev_Part_Str_1 = PartingString(prev)
        next_Part_Str_1 = NextString(prev)
        is_Special_Point_1 = isSpecialPoint(next_Part_Str_1)
        no_Letter_Part_1 = isContainLetter(next_Part_Str_1)
        prev_Part_Str_2 = PartingString(next)
        next_Part_Str_2 = NextString(next)
        is_Special_Point_2 = isSpecialPoint(next_Part_Str_2)
        no_Letter_Part_2 = isContainLetter(next_Part_Str_2)
        newCode = Rule(no_Letter_Part_1,no_Letter_Part_2)
        if (is_Special_Point_2==0):
          return (prev_Part_Str_2+'a'+newCode)
        elif (is_Special_Point_2==1):
          return (prev_Part_Str_2+'s'+newCode)
        else:
          return (prev_Part_Str_2+newCode)
     
        
def Rule(prev,next):
    if (prev==''):
      prev = '0'
    if (next==''):
      next = '9'
    
    if (len(prev)>len(next)):
      for i in range(len(prev)-len(next)):
        next = next+'0'
      length = len(next)
    elif (len(prev)<len(next)):
      for i in range(len(next)-len(prev)):
        prev = prev+'0'
        length = len(next)
    elif(len(prev)==len(next)):
        length = len(next)
        
    prev = string.atoi(prev)
    next = string.atoi(next)
  
    if ( length>len(str(next))):
      #说明next数字部分是以0开头的，要特殊处理
        if (prev ==0 and next == 1):
            code = isRide10(prev,next)
            for i in range(length):
                code = '0'+code
            return code
        else:
            length_next = length - len(str(next))
            code = isRide10(prev,next)
            for i in range(length_next):
                code = '0'+code
            return code
    else:
        if (prev ==0 and next == 1):
            code = isRide10(prev,next)
            for i in range(length):
                code = '0'+code
            return code
        else:
            if ((next-prev)==1):#等于1，两数相加后除2时，会有小数，应乘以10
                code = isRide10(prev,next)
                for i in range(length-len(str(prev))):
                    code = '0'+code
                return code
            else:
                code = isRide10(prev,next)
                for i in range(length-len(code)):
                    code = '0'+code
                return code

#是否要乘以10
def isRide10(prev,next):
    if((next-prev)==1):
      code = str(((next+prev)*10)/2)
    else:
      code = str((next+prev)/2)
    return code
      
       
def PartingString(strName):
    strlist = strName.split('-')
    sameStr = ''
    listLength = len(strlist)
    for i in range(listLength-1):
      sameStr = sameStr + strlist[i]+"-"
    return sameStr

def NextString(strName):
    strlist = strName.split('-')
    sameStr = ''
    listLength = len(strlist)
    sameStr =strlist[listLength-1]
    return sameStr

#是否包含字母
def isContainLetter(next_Part_Str):
    isA = next_Part_Str.find('a')
    if (isA==0):#存在a开头的字符
      a = next_Part_Str[1:]
    elif (isA==-1):
      isS = next_Part_Str.find('s')#特殊节点
      if (isS == 0):
        a = next_Part_Str[1:]
      elif (isS == -1):
        a = next_Part_Str
    return a
        
def isSpecialPoint(next_Part_Str):
    isA = next_Part_Str.find('a')
    if (isA==0):
      return 0
    elif(next_Part_Str.find('s')==0):
      return 1
    else:
      return -1

def getMainCode(code):
    codelist = code.split('-')
    return codelist[0]

#特殊节点
#将code再分解，确定是否要加's'标记   
def getReplyCode(code):
    codeStr = ''
    codelist = code.split('-')
    codeLength = len(codelist)
    for i in range(codeLength):
      if (codelist[i].find('s')==0):
        codeStr = code
        return codeStr
      else:
        if(i==(codeLength-1)):
          codeStr = codeStr +('s'+codelist[i])
        else:
          if(i==(codeLength-1)):
            codeStr = codeStr + codelist[i]
          else:
            codeStr = codeStr + codelist[i]+"-"
    return codeStr
        
##########搜索是否有子节点############
def findChildNodes(contentList,currentCode):
#    replyContents = db.GqlQuery("SELECT * FROM ReplyContent WHERE father=:1 ",currentCode)
    replyContents = db.GqlQuery("SELECT * FROM ReplyContent WHERE code > :1 AND  code < :2 AND status='1' ORDER BY code ASC", currentCode+'-',currentCode+'-'+u"\ufffd")
#    contents = db.GqlQuery("SELECT * FROM ContentClass WHERE father=:1 ",currentCode)
    contents = db.GqlQuery("SELECT * FROM ContentClass WHERE code > :1 AND  code < :2 AND status='1' ORDER BY code ASC", currentCode+'-',currentCode+'-'+u"\ufffd")
    if replyContents:
      for replyContent in replyContents:
        contentList.append(replyContent)
#        findChildNodes(contentList,replyContent.code)

    if contents:
      for content in contents:
        contentList.append(content)
#        findChildNodes(contentList,content.code)
        
    return contentList    
##########搜索############
def findFather(father):
    fatherList = []
    fatherCodeList = []
    fList = ''
    father_list = father.split('-')
    for i in range(len(father_list)):
      fList = fList + father_list[i]
      fatherCodeList.append(fList)
      fList = fList+"-"

    for i in range(len(fatherCodeList)):
      if ( fatherCodeList[i].find('s')!=-1):
        replyContents = db.GqlQuery("SELECT * FROM ReplyContent WHERE code=:1 ",fatherCodeList[i])
        for replyContent in replyContents:
          fatherList.append(replyContent)
      else:  
        contents = db.GqlQuery("SELECT * FROM ContentClass WHERE code=:1 ",fatherCodeList[i])
        for content in contents:
          fatherList.append(content)
    return fatherList

#删除过时的资讯######
def deleteTimedContent():
    contents = db.GqlQuery("SELECT * FROM ContentClass")
    for content in contents:
          if content.code:
                delta = datetime.datetime.now()-content.lastUpdateTime
                if content.status == '0':
                      if delta > datetime.timedelta(days=10):
                            db.delete(content)
